/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkFile, ArkMethod, ts, AstTreeUtils } from "arkanalyzer";
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from "../BaseChecker";
import { FileMatcher, MatcherCallback, MatcherTypes, MethodMatcher } from '../../Index';
import { Defects, IssueReport } from "../../model/Defects";
import { Rule } from "../../model/Rule";
import { RuleListUtil } from "../../utils/common/DefectsList";

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ExplicitModuleBoundaryTypesCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: "docs/explicit-module-boundary-types-check.md",
    description: "Require explicit return and argument types on exported functions' and classes' public class methods",
};
const defaultOptions: Options = {
    allowArgumentsExplicitlyTypedAsAny: false,
    allowDirectConstAssertionInArrowFunctions: true,
    allowedNames: [],
    allowHigherOrderFunctions: true,
    allowTypedFunctionExpressions: true,
}
interface Options {
    /** Whether to ignore arguments that are explicitly typed as `any`. */
    allowArgumentsExplicitlyTypedAsAny?: boolean;
    /**
     * Whether to ignore return type annotations on body-less arrow functions that return an `as const` type assertion.
     * You must still type the parameters of the function.
     */
    allowDirectConstAssertionInArrowFunctions?: boolean;
    /**
     * Whether to ignore return type annotations on functions immediately returning another function expression.
     * You must still type the parameters of the function.
     */
    allowHigherOrderFunctions?: boolean;
    /** Whether to ignore type annotations on the variable of a function expresion. */
    allowTypedFunctionExpressions?: boolean;
    /** An array of function/method names that will not have their arguments or return values checked. */
    allowedNames?: string[];
}

// 定义一个接口，用于存储函数或方法的行列信息
interface LocationInfo {
    fileName: string;
    line: number;
    character: number;
}

export class ExplicitModuleBoundaryTypesCheck implements BaseChecker {

    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private methodMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD,
    };

    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE,
    };

    public registerMatchers(): MatcherCallback[] {
        const methodMatcherCb: MatcherCallback = {
            matcher: this.methodMatcher,
            callback: this.check
        }
        const fileMatcherCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        }
        return [fileMatcherCb, methodMatcherCb];
    }

    public check = (target: ArkFile | ArkMethod) => {
        if (target instanceof ArkFile) {
            const targetName = target.getName();
            if (targetName && this.getFileExtension(targetName) === ".ets") {
                return;
            }
            const code = target.getCode();
            if (!code) {
                return;
            }
            const filePath = target.getFilePath();
            const sourceFile = AstTreeUtils.getASTNode(target.getName(), code);
            const missingReturnTypes = this.checkExplicitBoundaryType(sourceFile);
            missingReturnTypes.forEach(info => {
                this.addIssueReportNode(info.line, info.character, filePath);
            });
        }

        if (target instanceof ArkMethod) {
            const methodCode = target.getCode() ?? '';
            const methodName = target.getName() ?? '';
            if (this.isArrowFunction(methodCode)) {
                const Options: Options = (this.rule.option as unknown as Options) ?? defaultOptions;
                if (Options.allowedNames && Options.allowedNames.length !== 0) {
                    if (methodName && Options.allowedNames.includes(methodName)) {
                        return;
                    }
                }
                // 判断箭头函数的参数部分为空且有返回类型注解
                if (this.hasExplicitNoParameter(methodCode)) {
                    return
                }
                // 箭头函数的参数部分包含参数且有返回类型注解
                if (!this.hasExplicitParameterTypes(methodCode)) {
                    this.addIssueReport(target)
                }
            }
        }
    }

    private getFileExtension(filePath: string): string {
        const lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex === -1) {
            return '';
        }
        return filePath.substring(lastDotIndex);
    }

    public checkExplicitBoundaryType(sourceFile: ts.SourceFile): LocationInfo[] {
        const result: LocationInfo[] = [];
        const Options: Options = this.rule && this.rule.option[0] ? this.rule.option[0] as Options : defaultOptions;

        // 遍历源文件中的所有节点
        function visit(node: ts.Node) {
            if (ts.isFunctionDeclaration(node)
                || ts.isMethodDeclaration(node)
                || ts.isArrowFunction(node)
                || ts.isFunctionExpression(node)
            ) {
                if (Options.allowDirectConstAssertionInArrowFunctions && ts.isArrowFunction(node) && ts.isDeleteExpression(node)) {
                    return;
                }
                if (Options.allowTypedFunctionExpressions && ts.isTypeOfExpression(node)) {
                    return;
                }
                if (Options.allowedNames && Options.allowedNames.length !== 0) {
                    let methodName: string | undefined;
                    methodName = node.name?.getText();
                    if (methodName && Options.allowedNames.includes(methodName)) {
                        return;
                    }
                }
                // 检查是否有返回类型注解
                if (!node.type) {
                    const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
                    if (ts.isArrowFunction(node)) {
                        // 找到箭头函数的 => 符号的位置
                        const arrowToken = (node as ts.ArrowFunction).equalsGreaterThanToken;
                        if (arrowToken) {
                            const { line: arrowLine, character: arrowChar } = sourceFile.getLineAndCharacterOfPosition(arrowToken.getStart());
                            result.push({
                                fileName: sourceFile.fileName,
                                line: arrowLine + 1, // 行号从1开始
                                character: arrowChar + 1 // 列号从1开始
                            });
                        }
                    } else {
                        // 检查方法是否被 export 修饰
                        if (ts.getModifiers(node)?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
                            result.push({
                                fileName: sourceFile.fileName,
                                line: line + 1, // 行号从1开始
                                character: character + 8 // 列号从8开始
                            });
                        } else {
                            let current = node.parent;
                            let isExport = false;
                            // 检查父类是否被 export 修饰
                            const classDeclaration = current as ts.ClassDeclaration;
                            if (classDeclaration && ts.getModifiers(classDeclaration)?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
                                isExport = true;
                            }
                            if (isExport) {
                                result.push({
                                    fileName: sourceFile.fileName,
                                    line: line + 1, // 行号从1开始
                                    character: character + 1 // 列号从1开始
                                });
                            }
                        }
                    }
                }
            }
            ts.forEachChild(node, visit);
        }
        visit(sourceFile);
        return result;
    }

    private hasExplicitParameterTypes(code: string): boolean {
        // 正则表达式匹配箭头函数的参数部分包含参数且有返回类型注解
        const arrowFunctionParamRegex = /(\w+\s*=\s*)?\(([^)]+)\)\s*:\s*\w+\s*=>/;
        const match = code.match(arrowFunctionParamRegex);

        if (!match) {
            return true; // 没有匹配到箭头函数或没有返回类型注解
        }

        if (!match[2]) {
            return false; // 参数部分为空
        }
        const params = match[2].split(',').map(param => param.trim());
        // 检查每个参数是否有类型注解
        for (const param of params) {
            if (!/:/.test(param) || /: any/.test(param)) {
                return false; // 如果参数没有类型注解，返回 false
            }
        }
        return true; // 所有参数都有类型注解且有返回类型注解
    }

    private hasExplicitNoParameter(code: string): boolean {
        // 正则表达式匹配箭头函数的参数部分为空且有返回类型注解
        const arrowFunctionParamRegex = /(\w+\s*=\s*)?\(\s*\)\s*:\s*\w+\s*=>/;
        const match = code.match(arrowFunctionParamRegex);
        if (!match) {
            return false; // 没有匹配到箭头函数或没有返回类型注解
        }
        return true; // 参数部分为空且有返回类型注解
    }

    // 检查是否是箭头函数
    public isArrowFunction(code: string): boolean {
        const arrowFunctionRegex = /\s*=>\s*/;
        return arrowFunctionRegex.test(code);
    }

    private addIssueReportNode(line: number, startCol: number, filePath: string) {
        const severity = this.rule.alert ?? this.metaData.severity;
        const fixKey = line + '%' + startCol + '%' + this.rule.ruleId;
        const mergeKey = filePath + '%' + fixKey + '%' + this.metaData.description;
        const defect = new Defects(line, startCol, this.metaData.description, severity, this.rule.ruleId,
            mergeKey, this.metaData.ruleDocPath, true, false, false, fixKey)
        this.issues.push(new IssueReport(defect, undefined));
        RuleListUtil.push(defect);
    }

    private addIssueReport(arkMethod: ArkMethod) {
        const warnInfo = this.getLineAndColumn(arkMethod);
        const severity = this.rule.alert ?? this.metaData.severity;
        const fixKey = warnInfo.line + '%' + warnInfo.startCol + '%' + this.rule.ruleId;
        const mergeKey = warnInfo.filePath + '%' + fixKey + '%' + this.metaData.description;
        const defect = new Defects(warnInfo.line, warnInfo.startCol, this.metaData.description, severity, this.rule.ruleId,
            mergeKey, this.metaData.ruleDocPath, true, false, false, fixKey)
        this.issues.push(new IssueReport(defect, undefined));
        RuleListUtil.push(defect);
    }

    private getLineAndColumn(arkMethod: ArkMethod) {
        let line = arkMethod.getLine() ?? 0;
        const arkFile = arkMethod.getDeclaringArkFile();
        if (arkFile) {
            const methodCode = arkMethod.getCode() ?? '';
            let startCol = arkMethod.getColumn() ?? 0;
            const pos = methodCode.indexOf("(") + 1;
            if (pos !== -1) {
                startCol += pos;
                const originPath = arkFile.getFilePath();
                return { line, startCol, filePath: originPath }
            }
            return { line, startCol }
        } else {
            logger.debug('originStmt or arkFile is null');
        }
        return { line: -1, startCol: -1, filePath: "" };
    }
}
